package com.teen9g.infoplatformserver.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.teen9g.constant.ChatConstant;
import com.teen9g.dto.ChatMessageDTO;
import com.teen9g.entity.ChatMessage;
import com.teen9g.infoplatformserver.HttpEntity.DeepseekClient;
import com.teen9g.infoplatformserver.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@Controller
public class ChatWebSocketController {

    @Autowired
    private DeepseekClient deepseekClient;

    @Autowired
    private ChatService chatService;

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 处理发送消息的请求
     *
     * @param message 消息对象
     * @Payload 注解用于指定方法参数 message 的值是从 WebSocket 消息的负载中提取的
     */
    @MessageMapping("/sendMessage")
//    @SendToUser("/queue")
    public void sendMessage(@Payload ChatMessageDTO message) {
//        log.info("Received message: {}", mess     age);
//        // 保存消息到数据库
//        ChatMessage result = chatService.saveMessage(message);
//        return result;

        ChatMessage savedMessage = chatService.saveMessage(message);
        // 推送给发送方
        simpMessagingTemplate.convertAndSend(
                "/queue/private/" + message.getChatId(),
                savedMessage
        );
        // 推送给接收方
        simpMessagingTemplate.convertAndSendToUser(
                message.getReceiverId().toString(),
                "/queue/private/" + message.getChatId(),
                savedMessage
        );
    }

    /**
     * 处理发送消息的请求 (AI小助手)
     *
     * @param message 消息对象
     */
    @MessageMapping("/sendMessageWithAI")
    public void sendMessageWithAI(@Payload ChatMessageDTO message) throws IOException {
        //先保存用户发的消息
        ChatMessage savedMessage = chatService.saveMessageWithAI(message);

        //请求AI回复
        String AIReply = deepseekClient.callDeepSeek(message.getMessageContent());

        //解析出JSON数组里的choices数组里的text对象
        String text = null;
        try {
            // 创建ObjectMapper实例
            ObjectMapper objectMapper = new ObjectMapper();
            // 解析JSON字符串
            JsonNode rootNode = objectMapper.readTree(AIReply);
            // 获取choices数组
            JsonNode choicesNode = rootNode.get("choices");
            if (choicesNode != null && choicesNode.isArray()) {
                for (JsonNode choice : choicesNode) {
                    // 获取text属性值
                    JsonNode textNode = choice.get("text");
                    if (textNode != null) {
                        text = textNode.asText();
                        System.out.println("text属性值: " + text);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //将AI的回复解析成ChatMessage对象
        ChatMessage AIMessage = ChatMessage.builder()
                .chatId(message.getChatId())
                .senderId(ChatConstant.DEEPSEEK_USER_ID)
                .senderName(ChatConstant.DEEPSEEK_USER_NAME)
                .receiverId(message.getSenderId())
                .receiverName(message.getSenderName())
                .messageContent(text)
                .messageStatus(ChatConstant.CHAT_NOT_READ) // 默认消息状态为未读
                .deletedByReceiver(false) // 默认发送者可以阅读消息
                .deletedBySender(false) // 默认接收者可以阅读消息
                .sendTime(LocalDateTime.now()) // 设置发送时间
                .build();
        //保存AI的回复
        chatService.saveAIMessage(AIMessage);

        // 将用户发的消息推送
        simpMessagingTemplate.convertAndSend(
                "/queue/private/" + message.getChatId(),
                savedMessage
        );
        // 将AI的回复推送
        simpMessagingTemplate.convertAndSend(
                "/queue/private/" + message.getChatId(),
                AIMessage
        );
        // 推送给接收方
        simpMessagingTemplate.convertAndSendToUser(
                message.getReceiverId().toString(),
                "/queue/private/" + message.getChatId(),
                savedMessage
        );
        // 将AI的回复推送给接收方
        simpMessagingTemplate.convertAndSendToUser(
                message.getReceiverId().toString(),
                "/queue/private/" + message.getChatId(),
                AIMessage
        );
    }
}
